package com.kmproject.haifu.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.jess.arms.widget.CustomPopupWindow;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerMyStorySelectNewComponent;
import com.kmproject.haifu.mvp.contract.MyStorySelectNewContract;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MyStoryBean;
import com.kmproject.haifu.mvp.presenter.MyStorySelectNewPresenter;

import com.kmproject.haifu.R;
import com.kmproject.haifu.mvp.ui.adapter.MyStoryXZDPAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/01/2019 10:45
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MyStorySelectNewActivity extends BaseActivity<MyStorySelectNewPresenter> implements MyStorySelectNewContract.View {
    @BindView(R.id.toolbar_backImg)
    ImageView toolbarBackImg;
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.mystore_selectstory_popuwindow_RecyclerView)
    RecyclerView mystoreSelectstoryPopuwindowRecyclerView;
    @BindView(R.id.mystore_selectstory_popuwindow_add_txt)
    TextView mystoreSelectstoryPopuwindowAddTxt;
    @BindView(R.id.HouseRentingShowMain_refreshLayout)
    SmartRefreshLayout HouseRentingShowMainRefreshLayout;
    @BindView(R.id.HouseRentingShowMain_tsdp_txt)
    TextView HouseRentingShowMainTsdpTxt;
    @BindView(R.id.HouseRentingShowMain_tsdp_lay)
    LinearLayout HouseRentingShowMainTsdpLay;

    private MyStoryXZDPAdapter myStoryXZDPAdapter;//我的店铺适配器
    private int selectModel = 0;//选择店铺模式，默认0表示正常的选择店铺，1表示店铺管理，开启店铺
    ResultBean<List<MyStoryBean>> mresultBean;//我的店铺

    private MemberCenterUserInfoBean memberCenterUserInfoBean;
    private boolean openStore = false;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMyStorySelectNewComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_my_story_select_new; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
           if (getIntent().hasExtra("gotoAddStore"))
           {
               //去新增店铺
               Intent intent = new Intent(MyStorySelectNewActivity.this, MyStoryAddStoryActivity.class);
               ArmsUtils.startActivityForResult(intent, 1001);
               return;
           }

    }

    public MemberCenterUserInfoBean getMemberCenterUserInfoBean() {
        return memberCenterUserInfoBean == null ? (memberCenterUserInfoBean = (MemberCenterUserInfoBean) getIntent().getSerializableExtra("MemberCenterUserInfoBean")) : memberCenterUserInfoBean;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getMemberLevelByUser();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void listStoreSuccess(ResultBean<List<MyStoryBean>> resultBean) {
        //我的店铺列表
        loadMoreDatas(this, resultBean);
    }

    @Override
    public void enableStoreSuccess(int num) {
        //开启店铺成功后刷新界面
        selectModel = 0;
        //开启成功了用之前的+开启的个数
        memberCenterUserInfoBean.setIsShowStoreCount(memberCenterUserInfoBean.getIsShowStoreCount() + num);
        if (memberCenterUserInfoBean.getCanShowStoreCount() != -1) {
            memberCenterUserInfoBean.setCanShowStoreCount(memberCenterUserInfoBean.getCanShowStoreCount() - num);
        }
//        if (memberCenterUserInfoBean.getStoreCount()-memberCenterUserInfoBean.getIsShowStoreCount()>0&&(memberCenterUserInfoBean.getStoreTotal()>memberCenterUserInfoBean.getIsShowStoreCount()||memberCenterUserInfoBean.getStoreTotal()==-1))
        if (memberCenterUserInfoBean.getCanShowStoreCount() == -1 || memberCenterUserInfoBean.getCanShowStoreCount() > 0) {
            showMessage("剩余店铺可在“选择店铺-开启管理”进行开启！");
        } else {
            showMessage("店铺开启成功");
        }
        contralViewShow(memberCenterUserInfoBean);

    }

    @Override
    public void removeStoreSuccess() {
        showMessage("删除成功");
        myStoryXZDPAdapter.setNewData(null);
        mPresenter.listStore("1", selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求数据
    }

    @Override
    public void getMemberLevelByUserSuccess(MemberCenterUserInfoBean memberCenterUserInfoBean) {
        this.memberCenterUserInfoBean = memberCenterUserInfoBean;
        if (getIntent().hasExtra("selectModel")) {
            selectModel = 1;//直接来开启店铺的
            openStore = true;
        }
        showPopuWindowToXZDP(memberCenterUserInfoBean);
        contralViewShow(memberCenterUserInfoBean);
//        mPresenter.listStore("1", selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求数据
    }

    /**
     * 刷新我的店铺数据
     *
     * @param resultBean
     */
    public void loadMoreDatas(Activity activity, ResultBean<List<MyStoryBean>> resultBean) {
        HouseRentingShowMainRefreshLayout.finishLoadMore();
        if (resultBean == null || resultBean.getData() == null || resultBean.getData().isEmpty() || Integer.parseInt(resultBean.getExtra().getPage().getTotal()) < 1) {
            if (!myStoryXZDPAdapter.getData().isEmpty()) {
                myStoryXZDPAdapter.setNewData(null);
            }
            myStoryXZDPAdapter.setEmptyView(AppUtil.setEmptyView(activity, selectModel == 0 ? "你还没添加店铺哦！" : "没有待开启的店铺", null, null, true));
            HouseRentingShowMainRefreshLayout.setEnableLoadMore(false);
            return;
        }
        if (Integer.parseInt(resultBean.getExtra().getPage().getPages())==Integer.parseInt(resultBean.getExtra().getPage().getCurrent())) {
            //禁止刷新
            HouseRentingShowMainRefreshLayout.setEnableLoadMore(false);
        }
        mresultBean = resultBean;
        if (myStoryXZDPAdapter.getData().isEmpty() || Integer.parseInt(resultBean.getExtra().getPage().getCurrent()) == 1) {
            myStoryXZDPAdapter.setNewData(resultBean.getData());
        } else {
            myStoryXZDPAdapter.addData(resultBean.getData());
        }
    }

    /**
     * 控制选择店铺和选择开启店铺不同模式的控制
     *
     * @param
     * @param memberCenterUserInfoBean
     */
    public void contralViewShow(MemberCenterUserInfoBean memberCenterUserInfoBean) {
        if (myStoryXZDPAdapter != null) {
            myStoryXZDPAdapter.setMselectMode(selectModel);
        }
        if (selectModel == 0) {
            //选择店铺
            mystoreSelectstoryPopuwindowAddTxt.setText(ArmsUtils.getString(this, R.string.mystory_add));
//            if(memberCenterUserInfoBean.getStoreCount()-memberCenterUserInfoBean.getIsShowStoreCount()>0&&(memberCenterUserInfoBean.getStoreTotal()>memberCenterUserInfoBean.getIsShowStoreCount()||memberCenterUserInfoBean.getStoreTotal()==-1)&&memberCenterUserInfoBean.getIsNotShowReviewStatusStoreCount()>0)
            if (memberCenterUserInfoBean.getCanShowStoreCount() == -1 || memberCenterUserInfoBean.getCanShowStoreCount() > 0) {
                if (memberCenterUserInfoBean.getResidualTimeDay() < 1) {
                    //过期的就不显示开启管理
                    backRightTxt.setVisibility(View.INVISIBLE);
                } else {
                    if (memberCenterUserInfoBean.getCanShowStoreCount() > 0) {
                        backRightTxt.setVisibility(View.VISIBLE);
                    }
                }

            } else {
                backRightTxt.setVisibility(View.INVISIBLE);
            }

            toolbarTitle.setText(ArmsUtils.getString(this, R.string.mystory_title));
            HouseRentingShowMainTsdpLay.setVisibility(View.GONE);
            mPresenter.listStore("1", selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求数据

        } else {
            //选择经营的店铺
            mystoreSelectstoryPopuwindowAddTxt.setText(ArmsUtils.getString(this, R.string.mystory_qdkqjy));
            backRightTxt.setVisibility(View.INVISIBLE);

            toolbarTitle.setText(ArmsUtils.getString(this, R.string.mystory_xzjydp));
            if (memberCenterUserInfoBean.getStoreTotal() == -1 || memberCenterUserInfoBean.getCanShowStoreCount() == -1) {
//                HouseRentingShowMainTsdpTxt.setText("您还可以开启经营无限个店铺！");
//              不限的时候不提示
                HouseRentingShowMainTsdpLay.setVisibility(View.GONE);
            } else {
                if (openStore) {
                    HouseRentingShowMainTsdpTxt.setText("您购买的会员版本只能开启经营" + (memberCenterUserInfoBean.getCanShowStoreCount()) + "个店铺，请选择您要开启经营的店铺，确认开启后不能更换其他店铺经营，请谨慎开启！");

                } else {
                    HouseRentingShowMainTsdpTxt.setText("您还可以开启经营" + (memberCenterUserInfoBean.getCanShowStoreCount()) + "个店铺！");
                }
                HouseRentingShowMainTsdpLay.setVisibility(View.VISIBLE);
            }
            mPresenter.listStore("1", selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求数据
        }

    }


    /**
     * 控制popu控制选择店铺列表
     */
    public void showPopuWindowToXZDP(MemberCenterUserInfoBean memberCenterUserInfoBean) {

        toolbarTitle.setText(ArmsUtils.getString(this, R.string.mystory_title));
        toolbarTitle.setTextColor(ArmsUtils.getColor(this, R.color.white));
        toolbar.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_3F3F4B));
        toolbarBackImg.setImageResource(R.drawable.mystory_cancel_icon);
        backRightTxt.setText(ArmsUtils.getString(this, R.string.mystory_kqgl));
        backRightTxt.setTextColor(ArmsUtils.getColor(this, R.color.white));
        contralViewShow(memberCenterUserInfoBean);
        toolbarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectModel = 1;
                contralViewShow(memberCenterUserInfoBean);
            }
        });

        mystoreSelectstoryPopuwindowRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        myStoryXZDPAdapter = new MyStoryXZDPAdapter(memberCenterUserInfoBean, new ArrayList<>(), selectModel, mPresenter);
        mystoreSelectstoryPopuwindowRecyclerView.setAdapter(myStoryXZDPAdapter);
        myStoryXZDPAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);

        mystoreSelectstoryPopuwindowAddTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectModel == 1) {
                    //开启店铺的时候点击按钮
//                    萨达撒大大
                    mPresenter.enableStore(MyStorySelectNewActivity.this, memberCenterUserInfoBean, myStoryXZDPAdapter);
                    return;
                }

                if (memberCenterUserInfoBean.getStoreTotal() == 0) {
                    new AlertView("", "您当前会员等级暂不支持新增店铺，如需继续新增请升级会员等级！", "我知道了", new String[]{"去升级会员"}, null, MyStorySelectNewActivity.this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == AlertView.CANCELPOSITION) {
                                //点击取消按钮

                            } else {
                                Intent intent = new Intent(MyStorySelectNewActivity.this, MemberCenterUpdateLevelActivity.class);
                                intent.putExtra("MemberCenterUserInfoBean", memberCenterUserInfoBean);
                                ArmsUtils.startActivityForResult(intent, 1002);
                            }
                        }
                    }, ArmsUtils.getColor(MyStorySelectNewActivity.this, R.color.alert_button_00adfcr), true).show();

                    return;
                }
                //新增店铺
                if (memberCenterUserInfoBean.getStoreTotal() != -1 && memberCenterUserInfoBean.getStoreTotal() <= memberCenterUserInfoBean.getStoreCount()) {
                    //店铺数量超过上限
                    new AlertView("", "当前会员等级店铺数量已达上限，" +
                            "如需继续新增请升级会员等级！", "我知道了", new String[]{"去升级会员"}, null, MyStorySelectNewActivity.this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == AlertView.CANCELPOSITION) {
                                //点击取消按钮

                            } else {
                                Intent intent = new Intent(MyStorySelectNewActivity.this, MemberCenterUpdateLevelActivity.class);
                                intent.putExtra("MemberCenterUserInfoBean", memberCenterUserInfoBean);
                                ArmsUtils.startActivityForResult(intent, 1002);
                            }
                        }
                    }, ArmsUtils.getColor(MyStorySelectNewActivity.this, R.color.alert_button_00adfcr), true).show();
                    return;
                }
                Intent intent = new Intent(MyStorySelectNewActivity.this, MyStoryAddStoryActivity.class);
                ArmsUtils.startActivityForResult(intent, 1001);
            }
        });
        HouseRentingShowMainRefreshLayout.setEnableRefresh(false);//禁止下拉刷新
        HouseRentingShowMainRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //刷新
                if (mresultBean != null) {
                    mPresenter.listStore(String.valueOf(Integer.parseInt(mresultBean.getExtra().getPage().getCurrent()) + 1), selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求下一页
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (selectModel == 1) {
            selectModel = 0;
            contralViewShow(memberCenterUserInfoBean);
            return;
        }
        super.onBackPressed();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            //刷新数据
            if (data.hasExtra("type")) {
                //新添加成功，店铺数量更新加1
                memberCenterUserInfoBean.setStoreCount(memberCenterUserInfoBean.getStoreCount() + 1);
            }
            mPresenter.listStore("1", selectModel == 0 ? "" : "0", selectModel == 0 ? "" : "2");//请求数据
        } else {
            //去升级回来的

        }
    }
}
